﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PowerBooking.RSE.Domain.Models;
using PowerBooking.RSE.Utility.Helpers;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using PowerBooking.RSE.Repository;
using System.Data.Entity;
using PowerBooking.RSE.Poco;
using System.Data.Objects;

namespace PowerBooking.RSE.Domain.Factories
{
    /// <summary>
    /// 城市工厂
    /// </summary>
    public class CityFactory : Factory
    {
        public CityFactory(ObjectContext objectContext) : base(objectContext) { }

        /// <summary>
        /// 创建订餐小秘书城市集合
        /// </summary>
        /// <returns></returns>
        public List<City> CreateXiaomishuCities(int spiderID, string url)
        {
            var cityList = new ConcurrentBag<City>();
            var html = HttpHelper.Get(url);
            var matches = Regex.Matches(html, GetXiaomishuCitiesParttern(), RegexOptions.Singleline | RegexOptions.IgnoreCase).OfType<Match>().ToList();
            Parallel.ForEach(matches, (m) =>
            {
                if (!CacheHelper.Get<bool>("IsCaptureStop"))
                {
                    var cityPoco = new CityPoco()
                    {
                        Name = m.Groups[2].Value,
                        Url = m.Groups[1].Value,
                        SpiderID = spiderID
                    };
                    CityRepository.InsertCity(cityPoco);
                    cityList.Add(new City().InitDomain(cityPoco));
                }
                else
                {
                    return;
                }
            });

            return cityList.ToList();
        }

        /// <summary>
        /// 创建订餐小秘书城市集合正则
        /// </summary>
        /// <returns></returns>
        private string GetXiaomishuCitiesParttern()
        {
            var attributes = RegexHelper.CreateAttribute("href", RegexHelper.AnyAttributeValueInGroup) + RegexHelper.Space + RegexHelper.CreateAttribute("class", @"dib mr15 mb10" + RegexHelper._Space + @"[b]?");
            return RegexHelper.CreateDom("a", attributes, RegexHelper.AnyDomValueInGroup);
        }
    }
}
